<?php
/**
 * 表情管理
 * Date: 2020/8/11
 * Author: sunlinxin
 */
namespace Frieza\Modules\Emoticon\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\service\Emoticons as sEmoticons;
use Doraemon\model\Emoticons as mEmoticons;

class EmoticonController extends Controller
{
    public function list(Request $request, Content $content)
    {
        $params = $request->input();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        $search = [];
        if (isset($params['emo_name']) && $params['emo_name']) {
            $search['emo_name[~]'] = $params['emo_name'];
        }
        if (isset($params['emo_type']) && $params['emo_type']) {
            $search['emo_type'] = $params['emo_type'];
        }
        if (isset($params['is_common']) && $params['is_common'] < 2) {
            $search['is_common'] = $params['is_common'];
        }
        if (isset($params['emo_status']) && $params['emo_status']) {
            $search['emo_status'] = $params['emo_status'];
        }

        $list = sEmoticons::getEmoPageList($page, $pageSize, $search);
        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function($filter){
                    $filter->disableIdFilter();
                    $filter->like('emo_name', '名称');
                    $filter->equal('emo_type', '类型')->radio([
                        '' => '全部',
                        mEmoticons::EMO_TYPE_EMOJI => 'emoji表情',
                        mEmoticons::EMO_TYPE_CUSTOMIZE => '好好住表情'
                    ]);
                    $filter->equal('is_common', '是否常用')->radio([
                        2 => '全部',
                        0 => '否',
                        1 => '是'
                    ])->default('2');
                    $filter->equal('emo_status', '状态')->radio([
                        '' => '全部',
                        mEmoticons::EMO_STATUS_NORMAL => '启用',
                        mEmoticons::EMO_STATUS_DELETED => '禁用'
                    ]);
                });

                $grid->column("id", 'ID');
                $grid->column("icon", '表情')->display(function () {
                    if ($this->emo_type == mEmoticons::EMO_TYPE_EMOJI) {
                        $str = strtolower(ltrim($this->unicode_str, 'U+'));
                        return '<span class="emoji emoji'.$str.'"></span>';
                    } else {
                        return '<img src="'.$this->emo_src.'" style="width:20px;height:20px;" />';
                    }
                });
                $grid->column("emo_name", '名称');
                $grid->column("emo_type", '类型')->using(mEmoticons::EMO_TYPE);
                $grid->column("sort", '排序');
                $grid->column("is_common", '是否常用')->using([0=>'否',1=>'是']);
                $grid->column("emo_status", '状态')->using(mEmoticons::EMO_STATUS);
                $grid->column("addtime", '添加时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->addtime);
                });
                $grid->column("edittime", '更新时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime);
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            });

        $tab = new Tab();
        $tab->add('表情列表', $gridList->render(), true);
        $tab->addLink('新增表情', url('admin/emoticon/create'));
        $content->row($tab);
        return $content
            ->header('表情管理')
            ->description(' ')
            ->breadcrumb(['text' => '表情列表']);
    }

    public function create(Request $request, Content $content, $id = 0)
    {
        $emoRow = [];
        if ($id) {
            $header = '编辑表情';
            $emoRow = sEmoticons::getSingleEmoticon($id);
        } else {
            $header = '新增表情';
        }
        $tab = new Tab();
        $form = new Form($emoRow);

        if ($id > 0) {
            $form->hidden('id');
            $form->text('emo_name', '名称')->required()->help("示例：微笑")->readonly();
        } else {
            $form->text('emo_name', '名称')->required()->help("示例：微笑")->attribute(['autocomplete' => 'off']);
        }
        $form->fieldChange('emo_type', '类型', $form)
            ->options(mEmoticons::EMO_TYPE)
            ->default(mEmoticons::EMO_TYPE_EMOJI)
            ->required()
            ->callablePreCommon(function (Form $form){
            })->callableMap([
                mEmoticons::EMO_TYPE_EMOJI => function (Form $form) {
                    $form->text('unicode_str', 'Unicode')->required()->help("示例：U+1F603");
                },
                mEmoticons::EMO_TYPE_CUSTOMIZE => function (Form $form) {
                    $form->imgUpload('emo_pic_id','上传图片');
                }
            ]);
        $form->number('sort', '排序')->min(1)->default(50)->help("数字越小排序越靠前");
        $form->radio('is_common', '是否常用')->options([0=>'否',1=>'是'])->default(0);
        if ($id) {
            $form->radio('emo_status', '状态')->options(mEmoticons::EMO_STATUS)->default(mEmoticons::EMO_STATUS_NORMAL);
        }
        $form->action(url('admin/emoticon/save'));

        $tab->addLink('表情列表', url('admin/emoticon/list'));
        $tab->add($header, $form->render(), true);
        return $content->header('表情管理')
            ->breadcrumb(
                ['text' => $header])
            ->row($tab);
    }

    public function save(Request $request, Content $content)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $result = sEmoticons::saveEmoticon($params);
            if ($result) {
                return redirect(url('/admin/emoticon/list'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }
}